package com.tzu.ft.transfer.client;

import com.tzu.ft.base.TransferTools;
import com.tzu.ft.transfer.ClientUI;
import com.tzu.ssl.KeyInfo;
import com.tzu.ssl.SSLTools;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManagerFactory;
import java.io.FileInputStream;
import java.security.KeyStore;

/**
 * * 客户端实现类，ssl
 */
public class FTSSLClient extends Client {

	/**
	 * <ul>
	 * <li>ssl连接的重点:</li>
	 * <li>初始化SSLSocket</li>
	 * <li>导入客户端私钥KeyStore，导入客户端受信任的KeyStore(服务端的证书)</li>
	 * </ul>
	 */
	@Override
	public void init(String host, int port, KeyInfo keyInfo, ClientUI ui) {
		this.host = host;
		this.port = port;
		this.ui = ui;
		try {
			char[] password = keyInfo.getKeypass().toCharArray();
			KeyStore ks = KeyStore.getInstance(keyInfo.getKeyStoreType());
			ks.load(new FileInputStream(keyInfo.getKeyStorePath()), password);
			KeyManagerFactory kmf = KeyManagerFactory.getInstance(SSLTools.SUN_X509);
			kmf.init(ks, password);

			KeyStore tks = KeyStore.getInstance(keyInfo.getKeyStoreType());
			TrustManagerFactory tmf = TrustManagerFactory.getInstance(SSLTools.SUN_X509);
			tks.load(new FileInputStream(keyInfo.getTrustStorePath()), password);
			tmf.init(tks);

			SSLContext ctx = SSLContext.getInstance(keyInfo.getSslVersion());
			// ctx.init(null, tmf.getTrustManagers(), null); // 单向验证
			ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
			socket = (SSLSocket) ctx.getSocketFactory().createSocket(host, port);
//			socket.setSoTimeout(TransferTools.DEFAULT_SO_TIMEOUT);
			socket = TransferTools.settingClient(socket);
		} catch (Exception e) {
			System.out.println(e);
		}
	}

}
